package com.atguigu.tingshu.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.common.util.MD5;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.order.LocalMsg;
import com.atguigu.tingshu.model.order.OrderDerate;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.order.adapter.PayWay;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.order.mapper.LocalMsgMapper;
import com.atguigu.tingshu.order.mapper.OrderDerateMapper;
import com.atguigu.tingshu.order.mapper.OrderDetailMapper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    /*
     * @description: TODO 订单结算页
     * @author: yyj
     * @date: 2025-02-10
     */
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private UserInfoFeignClient userInfoFeignClient;
    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private OrderDerateMapper orderDerateMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private LocalMsgMapper localMsgMapper;

    @Autowired
    private List<PayWay> payWays;
    @Autowired
    private RabbitService rabbitService;


    @Override
    public OrderInfoVo trade(TradeVo tradeVo) {
        //1.获取付款项类型
        Long userId = AuthContextHolder.getUserId();
        String itemType = tradeVo.getItemType();
        OrderInfoVo orderInfoVo = null;

        // 2.分别处理三种付款类型
        switch (itemType) {
            case "1001":
                orderInfoVo = dealAlbumTypeItem(tradeVo, userId, itemType);
                break;
            case "1002":
                orderInfoVo = dealTrackTypeItem(tradeVo, userId, itemType);
                break;
            case "1003":
                orderInfoVo = dealVipTypeItem(tradeVo, userId, itemType);

        }
        String sign = SignHelper.getSign(JSONObject.parseObject(JSONObject.toJSONString(orderInfoVo), Map.class));
        orderInfoVo.setSign(sign);

        //获取购买的商品
        if (CollectionUtils.isEmpty(orderInfoVo.getOrderDetailVoList())) {
            return orderInfoVo;
        }
        List<Long> payProductIds  = orderInfoVo.getOrderDetailVoList().stream().map(OrderDetailVo::getItemId).collect(Collectors.toList());
        String encrypt = MD5.encrypt(payProductIds.toString());
        String multiportRepeatKey=userId+":"+encrypt;
        redisTemplate.opsForValue().set(multiportRepeatKey,"1");

        // 3.返回不同付款项的结算页数据
        return orderInfoVo;
    }

    @Override
    public Map<String, Object> submitOrder(OrderInfoVo orderInfoVo) {
        Long userId = AuthContextHolder.getUserId();
        //1.校验(非法请求,黑白名单,订单完整性)
        //1.1非法请求
        String tradeNo = orderInfoVo.getTradeNo();
        if (tradeNo==null){
            throw new GuiguException(201,"非法请求");
        }
        //1.2签名校验 (序列化和反序列化操作)  todo Map.class这个中的payway有值 上面那个没有 不能相等
        String jsonString = JSONObject.toJSONString(orderInfoVo);
        Map checkDataMap = JSONObject.parseObject(jsonString, Map.class);
        checkDataMap.put("payWay","");// todo 所以再放一个key,给个空覆盖前一次的值
        try {
            SignHelper.checkSign(checkDataMap);
        } catch (Exception e) {
            log.error("签名验证失败: {}", e.getMessage(), e);
        }


        //1.3避免重复提交 幂等性处理
        /*todo 面试必问:接口幂等性如何保证:
                    1.锁机制(本地锁,分布式)
                    2.Redis+token(判断和删除(原子操作)要放在业务代码前操作)
                    3.数据库的唯一索引+防重表+事务机制
         */
        //用redis+md5+mysql
        List<Long> payProductIds  = orderInfoVo.getOrderDetailVoList().stream().map(OrderDetailVo::getItemId).collect(Collectors.toList());
        String encrypt = MD5.encrypt(payProductIds.toString());
        String multiportRepeatKey=userId+":"+encrypt;
        String script = "if redis.call(\"exists\",KEYS[1])\n" + "then\n" + "    return redis.call(\"del\",KEYS[1])\n" + "else\n" + "    return 0\n" + "end";
        Long execute = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(multiportRepeatKey));
        if (execute==0){
            throw new GuiguException(ResultCodeEnum.REPEAT_SUBMIT);
        }
        //1.4生成订单编号
        String orderNo  = RandomStringUtils.random(15, true, false);
        //支付方式
        String payWay = orderInfoVo.getPayWay();
        //不同支付方式
        for (PayWay way : payWays) {
            if (way.supportPayWay(payWay)){
                way.payWay(orderInfoVo,orderNo,userId);
            }
        }

        //2.保存订单信息
        //3.返回订单编号
        HashMap<String, Object> map = new HashMap<>();
        map.put("orderNo", orderNo);
        return map;
    }

    @Override
    public OrderInfo saveOrderInfo(OrderInfoVo orderInfoVo, String orderNo, Long userId) {
        OrderInfo orderInfo = null;
        try {
            // 1.保存订单基本信息
            orderInfo=saveOrderBasicInfo(orderInfoVo,orderNo,userId);
            // 2.保存订单减免信息
            saveOrderDerateInfo(orderInfoVo,orderInfo.getId());
            // 3.保存订单详情信息
            saveOrderDetailInfo(orderInfoVo, orderInfo.getId());
        } catch (Exception e) {
            throw new GuiguException(201,"服务器内部错误");
        }
        return orderInfo;
    }


    @Override
    public void saveLocalMsg(String orderNo) {
        LocalMsg localMsg = new LocalMsg();
        localMsg.setMsgContent(orderNo);
        localMsg.setStatus(0);
        localMsg.setCreateTime(new Date());
        localMsg.setUpdateTime(new Date());

        localMsgMapper.insert(localMsg);

    }

    @Override
    public void paySuccess(String orderNo) {
        // 1.根据订单编号查询订单信息
        OrderInfo orderInfo=getOrderInfoAndDetail(orderNo);
        if (orderInfo == null) {
            throw new GuiguException(201, "订单不存在");
        }
        // 2.修改订单状态
        int count = orderInfoMapper.updateOrderStatus(orderNo);
        if (count == 0) {
            log.error("订单状态未修改成功");
        } else {
            log.info("订单状态修改成功");
        }
        // 3.记录订单支付流水（3种情况）
        UserPaidRecordVo userPaidRecordVo = prepareUserPaidRecordMsgVo(orderInfo);
        rabbitService.sendMessage(MqConst.EXCHANGE_USER, MqConst.ROUTING_USER_PAY_RECORD, JSONObject.toJSONString(userPaidRecordVo));
        // 4.修改ES中专辑的购买量
        rabbitService.sendMessage(MqConst.EXCHANGE_ALBUM_ES_STAT_UPDATE, MqConst.ROUTING_ALBUM_ES_STAT_UPDATE, orderNo);
        // 5.修改MySQL中专辑以及声音的购买量（0402）
        rabbitService.sendMessage(MqConst.EXCHANGE_ALBUM, MqConst.ROUTING_ALBUM_STAT_UPDATE, orderNo);
    }

    //todo 记录订单支付流水（3种情况）
    private UserPaidRecordVo prepareUserPaidRecordMsgVo(OrderInfo orderInfo) {
        UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
        userPaidRecordVo.setOrderNo(orderInfo.getOrderNo());
        userPaidRecordVo.setUserId(orderInfo.getUserId());
        userPaidRecordVo.setItemType(orderInfo.getItemType());
        List<Long> collect = orderInfo.getOrderDetailList().stream().map(orderDetail -> orderDetail.getItemId()).collect(Collectors.toList());
        userPaidRecordVo.setItemIdList(collect);
        return userPaidRecordVo;
    }

    public OrderInfo getOrderInfoAndDetail(String orderNo) {
        // 1.查询订单的基本数据
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
        // 2.查询订单详情数据
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, orderInfo.getId()));
        // 3.查询订单减免数据
        List<OrderDerate> orderDerates = orderDerateMapper.selectList(new LambdaQueryWrapper<OrderDerate>().eq(OrderDerate::getOrderId, orderInfo.getId()));
        // 4.查询订单状态名字(0901 0902 0903)
        String orderStatus = orderInfo.getOrderStatus();
        String orderStatusName = getOrderStatusName(orderStatus);
        // 5.查询订单支付方式的名字(1101 1102 1103)
        String payWay = orderInfo.getPayWay();
        String payWayName = getPayWayName(payWay);
        // 6.封装
        orderInfo.setOrderStatus(orderStatusName);
        orderInfo.setPayWayName(payWayName);
        orderInfo.setOrderDetailList(orderDetails);
        orderInfo.setOrderDerateList(orderDerates);
        return orderInfo;
    }

    @Override
    public IPage<OrderInfo> findUserPage(IPage<OrderInfo> orderInfoPage, Long userId) {
        // 1.分页查询当前用户的所有订单
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getUserId, userId)
                .eq(OrderInfo::getIsDeleted, 0)
                .orderByDesc(OrderInfo::getCreateTime);
        IPage<OrderInfo> orderInfoIPage = page(orderInfoPage, wrapper);
        List<OrderInfo> orderInfoList = orderInfoIPage.getRecords();

        //遍历展示
        orderInfoList.stream().forEach(orderInfo -> {
            String orderStatus = orderInfo.getOrderStatus();
            orderInfo.setOrderStatusName(getOrderStatusName(orderStatus));
            String payWay = orderInfo.getPayWay();
            orderInfo.setPayWayName(getPayWayName(payWay));
            LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(OrderDetail::getOrderId, orderInfo.getId());
            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
            orderInfo.setOrderDetailList(orderDetailList);// 订单的详情（根据每一个订单查询该订单的订单详情）
            LambdaQueryWrapper<OrderDerate> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(OrderDerate::getOrderId, orderInfo.getId());
            List<OrderDerate> orderDerateList = orderDerateMapper.selectList(wrapper2);
            orderInfo.setOrderDerateList(orderDerateList);
        });
        return orderInfoPage.setRecords(orderInfoList);
    }

    //查询订单支付方式的名字(1101 1102 1103)
    private String getPayWayName(String payWay) {
        String payWayName = "";

        switch (payWay) {
            case "1101":
                payWayName = "微信支付";
                break;
            case "1102":
                payWayName = "支付宝支付";
                break;
            case "1103":
                payWayName = "余额支付";
        }
        return payWayName;
    }

    //查询订单状态名字(0901 0902 0903)
    private String getOrderStatusName(String orderStatus) {
        String orderStatusName = "";
        switch (orderStatus){
            case "0901":
                orderStatusName = "未支付";
                break;
            case "0902":
                orderStatusName = "已支付";
                break;
            case "0903":
                orderStatusName = "已关闭";
        }
        return orderStatusName;
    }

    // 3.保存订单详情信息
    private void saveOrderDetailInfo(OrderInfoVo orderInfoVo, Long orderId) {
        orderInfoVo.getOrderDetailVoList().stream().forEach(orderDetailVo -> {

            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setItemId(orderDetailVo.getItemId());
            orderDetail.setItemName(orderDetailVo.getItemName());
            orderDetail.setItemUrl(orderDetailVo.getItemUrl());
            orderDetail.setItemPrice(orderDetailVo.getItemPrice());
            int insert = orderDetailMapper.insert(orderDetail);
            log.info("保存订单详情信息到数据库{}", insert > 0 ? "成功" : "失败");
        });
    }

    // 2.保存订单减免信息
    private void saveOrderDerateInfo(OrderInfoVo orderInfoVo, Long orderId) {
        orderInfoVo.getOrderDerateVoList().stream().forEach(orderDerateVo -> {
            OrderDerate orderDerate = new OrderDerate();
            orderDerate.setOrderId(orderId);
            orderDerate.setDerateType(orderDerateVo.getDerateType());
            orderDerate.setDerateAmount(orderDerateVo.getDerateAmount());
            orderDerate.setRemarks(orderDerateVo.getRemarks());
            int insert = orderDerateMapper.insert(orderDerate);
            log.info("保存订单减免信息到数据库{}", insert > 0 ? "成功" : "失败");
        });
    }

    // 1.保存订单基本信息
    private OrderInfo saveOrderBasicInfo(OrderInfoVo orderInfoVo, String orderNo, Long userId) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setOrderTitle(orderInfoVo.getOrderDetailVoList().get(0).getItemName());
        orderInfo.setOrderNo(orderNo);
        orderInfo.setOrderStatus("0901");
        orderInfo.setOriginalAmount(orderInfoVo.getOriginalAmount());
        orderInfo.setDerateAmount(orderInfoVo.getDerateAmount());
        orderInfo.setOrderAmount(orderInfoVo.getOrderAmount());
        orderInfo.setItemType(orderInfoVo.getItemType());
        orderInfo.setPayWay(orderInfoVo.getPayWay());
        int insert = baseMapper.insert(orderInfo);
        log.info("保存订单信息到数据库{}",insert>0?"success":"false");
        return orderInfo;
    }

    /**
     * todo 处理付款项类型是专辑类型（1001）
     *
     * @param tradeVo
     * @param userId
     * @param itemType
     * @return
     */
    private OrderInfoVo dealAlbumTypeItem(TradeVo tradeVo, Long userId, String itemType) {
        // 1.创建OrderInfoVo
        OrderInfoVo orderInfoVo = new OrderInfoVo();

        // 2.幂等性校验
        // 2.1 判断购买项是否已经买过（支付完毕）
        Long albumId = tradeVo.getItemId();
        Result<Boolean> userPaidAlbumResult = userInfoFeignClient.getUserPaidAlbum(userId, albumId);
        Boolean isPaidAlbum = userPaidAlbumResult.getData();
        Assert.notNull(isPaidAlbum, "远程调用用户微服务获取购买过的专辑信息失败");
        if (isPaidAlbum) {
            log.error("该付款项目:{}已经购买过，请勿重复购买", albumId);
            throw new GuiguException(201, "该付款项目已经购买过，请勿重复购买");
        }
        // 2.2 判断购买项是否准备支付（支付中）
        int count = orderInfoMapper.checkAlbumAndVipTypeItemPadding(itemType, userId, albumId);
        if (count != 0) {
            log.error("该付款项专辑：{}，处于购买中，请勿继续购买该专辑", albumId);
            orderInfoVo.setExitItemIds(Lists.newArrayList(albumId));
            return orderInfoVo;
        } else {
            // 3.给OrderInfoVo赋值
            String tradeNo = RandomStringUtils.random(12, true, true);
            // 3.1 赋值订单交易号
            orderInfoVo.setTradeNo(tradeNo); // 订单的交易号（当订单不存在 跟踪订单信息）/订单编号（订单存在 跟踪订单信息）（跟踪订单信息）
            // 3.2 赋值订单支付方式
            orderInfoVo.setPayWay(""); // 不知道支付方式（付钱的时候才知道用哪种支付方式）
            // 3.3 赋值订单的付款项
            orderInfoVo.setItemType(tradeVo.getItemType()); // 付款项类型
            // 3.4 赋值订单的原始金额
            // 3.4.1 查询付款项的金额
            Result<AlbumInfo> alumInfoResult = albumInfoFeignClient.getAlbumInfo(albumId);
            AlbumInfo albumInfoData = alumInfoResult.getData();
            Assert.notNull(albumInfoData, "远程调用专辑微服务获取专辑信息失败");
            // 付款项价格（专辑价格）
            BigDecimal originalPrice = albumInfoData.getPrice();
            orderInfoVo.setOriginalAmount(originalPrice.setScale(2, BigDecimal.ROUND_HALF_UP)); // 订单的原始金额（优惠之前的价格）
            // 3.5 赋值订单的优惠金额
            // 3.5.1 查询当前登录用户对象
            Result<UserInfoVo> userInfoResult = userInfoFeignClient.getUserInfo(userId);
            UserInfoVo userInfoData = userInfoResult.getData();
            Assert.notNull(userInfoData, "远程调用用户微服务当前登录的用户信息失败");
            Integer isVip = userInfoData.getIsVip();
            BigDecimal discount = null;
            // 3.5.2 查询付款项的折扣力度
            if (isVip.equals("1")) {
                // 登录用户是vip
                discount = albumInfoData.getVipDiscount();
            } else {
                // 登录用户不是vip
                discount = albumInfoData.getDiscount();
            }
            if (discount.intValue() == -1) {
                // 没有折扣力度（不打折）
                discount = new BigDecimal("10.00");
            }
            // 3.5.3 计算优惠多少钱:原件：100 折扣力度：7 优惠：30=（100(原价)-[100（原价）*7（折扣力度）/10]）
            BigDecimal derateAmount = originalPrice.subtract(originalPrice.multiply(discount).divide(new BigDecimal("10.00")));
            orderInfoVo.setDerateAmount(derateAmount.setScale(2, BigDecimal.ROUND_HALF_UP));// 优惠多少钱 优惠金额
            BigDecimal orderAount = originalPrice.subtract(derateAmount);
            orderInfoVo.setOrderAmount(orderAount.setScale(2, BigDecimal.ROUND_HALF_UP));//  真正要花的钱 实际金额
            // 3.6 赋值订单的项数据
            ArrayList<OrderDetailVo> orderDetailVos = new ArrayList<>();
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(albumId);
            orderDetailVo.setItemName(albumInfoData.getAlbumTitle());
            orderDetailVo.setItemUrl(albumInfoData.getCoverUrl());
            orderDetailVo.setItemPrice(originalPrice); // 订单项实际金额
            orderDetailVos.add(orderDetailVo);
            orderInfoVo.setOrderDetailVoList(orderDetailVos); //订单项（到底买的是谁）信息

            // 3.7 赋值减免数据
            ArrayList<OrderDerateVo> orderDerateVos = new ArrayList<>();
            OrderDerateVo orderDerateVo = new OrderDerateVo();
            orderDerateVo.setDerateType("专辑折扣"); // 前端展示
            orderDerateVo.setDerateAmount(derateAmount); // 优惠多少
            orderDerateVo.setRemarks("订单减免类型专辑折扣减免");
            orderDerateVos.add(orderDerateVo);
            orderInfoVo.setOrderDerateVoList(Lists.newArrayList(orderDerateVos));// 减免项（到底哪个商品有减免）信息
            orderInfoVo.setTimestamp(System.currentTimeMillis());// 时间戳（未来在提交订单 判断订单失效行）

            // 4.返回订单项数据
            return orderInfoVo;
        }
    }

    /**
     * todo 处理付款项类型是声音类型（1002）
     *
     * @param tradeVo
     * @param userId
     * @param itemType
     * @return
     */

    private OrderInfoVo dealTrackTypeItem(TradeVo tradeVo, Long userId, String itemType) {
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        Long trackId =  tradeVo.getItemId();
        // 购买的声音集数（本集 后10集 后20集）
        Integer trackCount = tradeVo.getTrackCount();
        Result<TrackInfo> trackInfoResult = albumInfoFeignClient.getTrackInfoById(trackId);
        TrackInfo trackInfoData = trackInfoResult.getData();
        Assert.notNull(trackInfoData, "远程查询专辑微服务获取声音信息失败");

        Long albumId = trackInfoData.getAlbumId();
        Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfo(albumId);
        AlbumInfo albumInfoData = albumInfoResult.getData();
        Assert.notNull(albumInfoData, "远程查询专辑微服务获取专辑信息失败");
        // 2.幂等性校验
        // 2.1 综合方法（即能把买过的声音查询出来又能把买过的声音过滤掉 返回真正能买的声音）判断购买项是否已经买过（支付完毕）
        Result<List> canPayTrackList=albumInfoFeignClient.getPaidTrackAndFilterCanPayTrack(userId, albumId,trackCount, trackId);
        Integer code = canPayTrackList.getCode();
        if (code==400){
            List data = canPayTrackList.getData();
            //返回已经买过的声音
            orderInfoVo.setExitItemIds(data);
            return orderInfoVo;
        }
        // 经过一次过滤之后能买的声音
        List<Map> canPayTrackListData = canPayTrackList.getData();
        Assert.notNull(canPayTrackListData, "远程查询专辑微服务获取能购买的声音列表失败");
        // 2.2 判断要买的声音中有没有存在正在支付中的
        // a)将正在支付中的声音返回给前端（错误）
        // b)将不在支付中的声音返给前端（真正要展示）
        List<Long> paddingTrackIds = orderInfoMapper.checkTrackTypeItemPadding(itemType, userId);
        List<Map> paddingTrackIdList  = canPayTrackListData.stream().filter(map -> paddingTrackIds.contains(map.get("id"))).collect(Collectors.toList());
        List<Object> exitTrackList = new ArrayList<>();
        // 要买的有声音中有存在支付中，收集起来返回给前端
        if (!CollectionUtils.isEmpty(paddingTrackIdList)) {
            for (Map map : paddingTrackIdList) {
                exitTrackList.add(map.get("id"));
                log.error("该付款项声音：{}，处于购买中，请勿继续购买该声音", map.get("id"));
            }
            orderInfoVo.setExitItemIds(exitTrackList);
            return orderInfoVo;
        }else {
            orderInfoVo.setTradeNo(RandomStringUtils.random(12, true, true));
            orderInfoVo.setPayWay("");
            orderInfoVo.setItemType(tradeVo.getItemType());

            BigDecimal trackPrice = albumInfoData.getPrice();
            BigDecimal originAmount  = trackCount == 0 ? trackPrice : trackPrice.multiply(new BigDecimal(trackCount));
            orderInfoVo.setOriginalAmount(originAmount.setScale(2, BigDecimal.ROUND_HALF_UP)); // 原始价格
            orderInfoVo.setDerateAmount(new BigDecimal("0.00")); // 优惠价格
            orderInfoVo.setOrderAmount(new BigDecimal("0"));
            orderInfoVo.setOrderAmount(originAmount.setScale(2, BigDecimal.ROUND_HALF_UP));// 实际金额

            ArrayList<OrderDetailVo> orderDetailVos = new ArrayList<>();
            for (Map map : canPayTrackListData) {
                OrderDetailVo orderDetailVo = new OrderDetailVo();
                Object id = map.get("id");
                orderDetailVo.setItemId(Long.parseLong(id + ""));
                orderDetailVo.setItemName((String) map.get("trackTitle"));
                orderDetailVo.setItemUrl((String) map.get("coverUrl"));
                orderDetailVo.setItemPrice(trackPrice.setScale(2, BigDecimal.ROUND_HALF_UP));
                orderDetailVos.add(orderDetailVo);
            }
            orderInfoVo.setOrderDetailVoList(Lists.newArrayList(orderDetailVos));
            orderInfoVo.setTimestamp(System.currentTimeMillis());
            orderInfoVo.setOrderDerateVoList(Lists.newArrayList());// 声音不打折
            return orderInfoVo;
        }
    }

    /**
     * todo 处理付款项类型是vip类型（1003）
     *
     * @param tradeVo
     * @param userId
     * @param itemType
     * @return
     */
    private OrderInfoVo dealVipTypeItem(TradeVo tradeVo, Long userId, String itemType) {
        //套餐id
        Long itemId = tradeVo.getItemId();

        OrderInfoVo orderInfoVo = new OrderInfoVo();

        //校验vip是否付款中
        int padding = orderInfoMapper.checkAlbumAndVipTypeItemPadding(itemType, userId, itemId);
        if (padding != 0) {
            log.error("该付款项vip套餐：{}，处于购买中，请勿继续购买该专辑", itemId);
            orderInfoVo.setExitItemIds(Lists.newArrayList(itemId));
            return orderInfoVo;
        }
        // 3. 赋值
        orderInfoVo.setTradeNo(RandomStringUtils.random(12, true, true));
        orderInfoVo.setPayWay("");
        orderInfoVo.setItemType(itemType);
        // 3.1.获取套餐信息
        Result<VipServiceConfig> vipServiceConfigResult = userInfoFeignClient.getAllVipConfig(itemId);
        VipServiceConfig serviceConfigData = vipServiceConfigResult.getData();
        Assert.notNull(serviceConfigData, "远程查询用户微服务获取vip套餐失败");
        //3.2.获取套餐价格
        BigDecimal price = serviceConfigData.getPrice();
        orderInfoVo.setOriginalAmount(price.setScale(2, BigDecimal.ROUND_HALF_UP));
        BigDecimal discountPrice = serviceConfigData.getDiscountPrice();
        BigDecimal derateAmount = price.subtract(discountPrice).setScale(2, BigDecimal.ROUND_HALF_UP);
        //优惠的价格
        orderInfoVo.setDerateAmount(derateAmount);
        //实际价格
        orderInfoVo.setOrderAmount(discountPrice.setScale(2, BigDecimal.ROUND_HALF_UP));
        // 3.3 给订单项属性赋值
        List<OrderDetailVo> orderDetailVos = new ArrayList<>();
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setItemId(itemId);
        orderDetailVo.setItemName(serviceConfigData.getName());
        orderDetailVo.setItemUrl(serviceConfigData.getImageUrl());
        orderDetailVo.setItemPrice(discountPrice.setScale(2, BigDecimal.ROUND_HALF_UP));
        orderDetailVos.add(orderDetailVo);
        orderInfoVo.setOrderDetailVoList(Lists.newArrayList(orderDetailVos));
        ArrayList<OrderDerateVo> orderDerateVos = new ArrayList<>();

        OrderDerateVo orderDerateVo = new OrderDerateVo();
        orderDerateVo.setDerateType("VIP服务折扣");
        orderDerateVo.setDerateAmount(derateAmount);
        orderDerateVo.setRemarks("订单减免类型1406-VIP服务折扣");
        orderDerateVos.add(orderDerateVo);
        orderInfoVo.setOrderDerateVoList(Lists.newArrayList(orderDerateVos));
        orderInfoVo.setTimestamp(System.currentTimeMillis());
        return orderInfoVo;


    }
}
